package edu.hda.pt.client.connections.xsocket;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;

import edu.hda.pt.client.connections.PTClientXSocket;
import edu.hda.pt.utils.Stream.StreamState;

/**
 * Event handler for receiving asynchronous messages
 * 
 * @author Marc Hammerton
 * 
 */
public class ClientHandler implements IDataHandler {

	private PTClientXSocket client;

	/**
	 * Constructor setting the client object
	 * 
	 * @param client
	 *            - client object
	 */
	public ClientHandler(PTClientXSocket client) {
		this.client = client;
	}

	/**
	 * This method is called when a asynchronous message from the server is received. It
	 * notifies the client that a message is received.
	 *
	 * 
	 * @seeorg.xsocket.connection.IDataHandler#onData(org.xsocket.connection.INonBlockingConnection)
	 */
	@Override
	public boolean onData(INonBlockingConnection nbc) throws IOException,
			BufferUnderflowException, ClosedChannelException,
			MaxReadSizeExceededException {

		if (client.stream.getState() == StreamState.START) {
			client.stream.setState(StreamState.RUNNING);
		}
		int datasize = client.stream.getFs();
		nbc.readBytesByLength(datasize);

		synchronized (client) {
			client.notify();
		}

		return true;
	}

}
